﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using BrnMall.Core;
using BrnMall.Web.Framework;
using BrnMall.Manager.Domain.Distribution;
using BrnMall.Manager.Manager.Distribution;
using BrnMall.Manager.Manager.Store;
using BrnMall.Services;
using BrnMall.Web.StoreAdmin.Models;
using BrnMall.WeiXin.Sdk;

namespace BrnMall.Web.StoreAdmin.Controllers
{
    public class DistributorController : BaseStoreAdminController
    {
        #region 分销商等级
        public ActionResult DisGradeList()
        {
            var dis = DistributorManager.GetGradeList(WorkContext.StoreId, 0);
            var model = new DisGradeListModel
            {
                DisGradeList = dis.Select(MapFrom).ToList(),
            };
            MallUtils.SetAdminRefererCookie(Url.Action("DisGradeList"));
            return View(model);
        }

        public ActionResult AddOrEditDisGrade(int id = 0)
        {
            DisGradeModel model = new DisGradeModel();
            model.GradeType = 0;
            if (id > 0)
            {
                var dis = DistributorManager.GetGrade(id);
                if (dis == null)
                    return PromptView("等级不存在");
                model = MapFrom(dis);

            }
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return View(model);
        }


        public ActionResult DeleteGrade(int id)
        {
            var grade = DistributorManager.GetGrade(id);
            if (grade == null)
                return PromptView("等级不存在");
            if (grade.IsDefault)
                return PromptView("默认等级不能删除");
            if (DistributorManager.CheckGradeIsUsing(WorkContext.StoreId, id))
                return PromptView("该等级已被使用，不能删除");
            var r = DistributorManager.DeleteGrade(id);
            return PromptView(r > 0 ? "等级删除成功" : "等级删除失败");
        }

        [HttpPost]
        public ActionResult AddOrEditDisGrade(DisGradeModel model)
        {
            if (model.Id == 0 && DistributorManager.GetGrade(WorkContext.StoreId, model.Name, model.GradeType) != null)
                ModelState.AddModelError("Name", "名称已经存在");

            if (ModelState.IsValid)
            {
                var disGrade = new DisGrade()
                {
                    Name = model.Name ?? "",
                    Id = model.Id,
                    StoreId = WorkContext.StoreId,
                    BrokerageLimit = model.BrokerageLimit,
                    Description = model.Description ?? "",
                    FirstBrokerageRise = model.FirstBrokerageRise,
                    GradeType = model.GradeType,
                    IsDefault = model.IsDefault,
                    SecondBrokerageRise = model.SecondBrokerageRise,
                    ThirdBrokerageRise = model.ThirdBrokerageRise
                };

                if (disGrade.Id > 0)
                    DistributorManager.UpdateGrade(disGrade);
                else
                    DistributorManager.AddGrade(disGrade);
                if (disGrade.IsDefault)
                    DistributorManager.SetGradeAsDefault(disGrade.Id);
                return PromptView("等级设置成功");
            }
            MallUtils.SetAdminRefererCookie(Url.Action("AddOrEditDisGrade", "Distributor"));
            
            return View("AddOrEditDisGrade", model);
        }


        #endregion

        #region 代理商等级

        public ActionResult AgentGradeList()
        {
            var dis = DistributorManager.GetGradeList(WorkContext.StoreId, 1);
            var model = new DisGradeListModel
            {
                DisGradeList = dis.Select(MapFrom).ToList(),
            };
            MallUtils.SetAdminRefererCookie(Url.Action("AgentGradeList"));
            return View(model);
        }
        public ActionResult AddOrEditAgentGrade(int id = 0)
        {
            DisGradeModel model = new DisGradeModel();
            model.GradeType = 1;
            if (id > 0)
            {
                var dis = DistributorManager.GetGrade(id);
                if (dis == null)
                    return PromptView("等级不存在");
                model = MapFrom(dis);

            }
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return View(model);
        }
        [HttpPost]
        public ActionResult AddOrEditAgentGrade(DisGradeModel model)
        {
            if (model.Id == 0 && DistributorManager.GetGrade(WorkContext.StoreId, model.Name, model.GradeType) != null)
                ModelState.AddModelError("Name", "名称已经存在");

            if (ModelState.IsValid)
            {
                var disGrade = new DisGrade()
                {
                    Name = model.Name ?? "",
                    Id = model.Id,
                    StoreId = WorkContext.StoreId,
                    BrokerageLimit = model.BrokerageLimit,
                    Description = model.Description ?? "",
                    FirstBrokerageRise = model.FirstBrokerageRise,
                    GradeType = model.GradeType,
                    IsDefault = model.IsDefault,
                    SecondBrokerageRise = model.SecondBrokerageRise,
                    ThirdBrokerageRise = model.ThirdBrokerageRise
                };

                if (disGrade.Id > 0)
                    DistributorManager.UpdateGrade(disGrade);
                else
                    DistributorManager.AddGrade(disGrade);
                if (disGrade.IsDefault)
                    DistributorManager.SetGradeAsDefault(disGrade.Id);
                return PromptView("等级设置成功");
            }
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            MallUtils.SetAdminRefererCookie(Url.Action("AddOrEditAgentGrade", "Distributor"));
            return View("AddOrEditAgentGrade",model);
        }

        #endregion

        #region 分销商列表

        public ActionResult DistributorList(string disStoreName, int gradeId = 0, int ordersTotalStart = 0, int ordersTotalEnd = 0, int pageSize = 15, int pageNumber = 1)
        {
            var dis = DistributorManager.GetDistributorList(WorkContext.StoreId, gradeId,disStoreName, ordersTotalStart,
                ordersTotalEnd, pageNumber, pageSize);
            var pageModel = new PageModel(pageSize, pageNumber, Convert.ToInt32(dis.TotalItems));
            var list = new DistributorListModel()
            {
                DistributorList = dis.Items.Select(CastFromDistributor).ToList(),
                OrdersTotalStart = ordersTotalStart,
                OrdersTotalEnd = ordersTotalEnd,
                GradeId = gradeId,
                DisStoreName=disStoreName,
                PageModel = pageModel
            };
            list.DisGrades = DistributorManager.GetGradeList(WorkContext.StoreId, 0)
                .Select(x => new SelectListItem() { Text = x.Name, Value = x.Id.ToString() }).ToList();
            list.DisGrades.Insert(0, new SelectListItem() { Selected = true, Text = "请选择", Value = "0" });
            MallUtils.SetAdminRefererCookie(Url.Action("DistributorList"));
            return View(list);
        }

        public ActionResult EditDistributor(int id)
        {
            var dis = DistributorManager.GetDistributor(id);
            var editModel = new DistributorEditModel
            {
                Id = dis.Id,
                DisStoreName = dis.DisStoreName,
                ShowLogo = dis.ShowLogo,
                LinkMan = dis.LinkMan,
                PhoneNumber = dis.PhoneNumber
            };
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return View(editModel);
        }

        public ActionResult DeleteDistributor(int id)
        {
            var dis = DistributorManager.GetDistributor(id);
            if (dis.IsAgent == 0) //分销商
            {
                var childDis = DistributorManager.GetDistributorChildList(dis.Id, dis.StoreId, 1, 10);
                if (childDis.TotalItems > 0)
                {
                    return PromptView("该分销商已有下级团队，不能删除！！");
                }

            }
            else//总代理
            {
                var childDis = DistributorManager.GetAgentChildList(dis.Id, 1, 10);
                if (childDis.TotalItems > 0)
                {
                    return PromptView("该代理商已有下级团队，不能删除！！");
                }
            }
            if(dis.AccountBalance>0||
                dis.OrdersCount>0||
                dis.OrdersTotal>0||
                dis.RequestBalance>0)
                return PromptView("不能删除已产生业务数据的分销商信息");

            DistributorManager.DeleteDistributor(id,WorkContext.StoreId);
            return PromptView("删除成功");
        }

        [HttpPost]
        public ActionResult EditDistributor(DistributorEditModel model)
        {
            var dis = DistributorManager.GetDistributor(model.Id);
            dis.DisStoreName = model.DisStoreName ?? "";
            dis.LinkMan = model.LinkMan ?? "";
            dis.PhoneNumber = model.PhoneNumber ?? "";
            DistributorManager.UpdateDistributor(dis);

            return PromptView("编辑成功");
        }
        public ActionResult ViewDistributor(int id, int pageNumber = 1, int pageSize = 15)
        {
            var dis = DistributorManager.GetDistributor(id);
            var myTeam = DistributorManager.GetDistributorChildList(id,dis.StoreId, pageNumber, pageSize);
            var viewModel = CastFromDistributor(dis);
            var br = BrokerageManager.GetBrokerageRequestUserListPage(viewModel.User.Uid, 1, 1, pageNumber, pageSize);
            viewModel.BrokerageRequest = br.Items;
            var pageModel = new PageModel(pageSize, pageNumber, Convert.ToInt32(br.TotalItems));
            var teamPageModel = new PageModel(pageSize, pageNumber, Convert.ToInt32(myTeam.TotalItems));
            viewModel.PageModel = pageModel;
            viewModel.TeamPageModel = teamPageModel;
            viewModel.TeamList = myTeam.Items.Select(CastFromDistributor).ToList();
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return View(viewModel);
        }
        public ActionResult SetDistributorStatus(int id, int status)
        {
            DistributorManager.SetDistributorStatus(id, status);
            return PromptView("操作成功");
        }
        

        public ActionResult OpenAgentFromDistributor(int id)
        {
            try
            {
                var result = DistributorManager.SetDistributorAsAgent(id);
                return PromptView(result ? "升级成功" : "升级失败");
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                return PromptView(e.Message);
            }

        }
       
        #endregion

        #region 代理商列表

        public ActionResult AgentList(string disStoreName, int gradeId = 0, int ordersTotalStart = 0, int ordersTotalEnd = 0,
            int pageSize = 15, int pageNumber = 1)
        {
            var dis = DistributorManager.GetDistributorAgentList(WorkContext.StoreId, gradeId,disStoreName, ordersTotalStart,
                ordersTotalEnd, pageNumber, pageSize);
            var pageModel = new PageModel(pageSize, pageNumber, Convert.ToInt32(dis.TotalItems));
            var list = new AgentListModel()
            {
                AgentList = dis.Items.Select(CastAgentFromDistributor).ToList(),
                OrdersTotalStart = ordersTotalStart,
                OrdersTotalEnd = ordersTotalEnd,
                GradeId = gradeId,
                DisStoreName = disStoreName,
                PageModel = pageModel
            };
            list.DisGrades = DistributorManager.GetGradeList(WorkContext.StoreId, 1)
                .Select(x => new SelectListItem() { Text = x.Name, Value = x.Id.ToString() }).ToList();
            list.DisGrades.Insert(0, new SelectListItem() { Selected = true, Text = "请选择", Value = "0" });
            MallUtils.SetAdminRefererCookie(Url.Action("AgentList"));
            return View(list);
        }

        public ActionResult OpenAgent(string userName, string email, string mobile, int pageSize = 15, int pageNumber = 1)
        {

            string condition = Users.GetUserListCondition("",userName, email, mobile, WorkContext.StoreId);

            var allDistributor = DistributorManager.GetAllDistributors(WorkContext.StoreId).Select(t => t.UserId.ToString())
                .ToArray();
            if (allDistributor.Length > 0)
            {
                condition += $" AND [bma_users].[uid] not in ({string.Join(",",allDistributor)})";
            }

            PageModel pageModel = new PageModel(pageSize, pageNumber, Users.GetUserCount(condition));



            OpenAgentListModel model = new OpenAgentListModel()
            {
                PageModel = pageModel,
                UserName = userName,
                Email = email,
                Mobile = mobile

            };
            var userList = Users.GetUserList(pageModel.PageSize, pageModel.PageNumber, condition);

            
            model.UserList = userList;
            MallUtils.SetAdminRefererCookie(Url.Action("OpenAgent"));
            return View(model);
        }

        public ActionResult OpenUserAgent(int userId)
        {
            var user = Users.GetPartUserById(userId);
            if (user == null)
                return PromptView("UserId不存在");
            var dis = new Distributor();
            //var ifexist = DistributorManager.GetDistributorByUserId(userId);
            //if (ifexist != null && ifexist.IsAgent == 0)
            //    return PromptView("分销商不能开通代理功能");
            //if (ifexist != null) return PromptView("已开通代理商功能");

            dis.IsAgent = 1;
            dis.UserId = userId;
            var defaultGrade = DistributorManager.GetGradeDefault(user.RegisterFromStoreId, 1);
            dis.GradeId = defaultGrade.Id;
            dis.ShowLogo = user.Avatar;
            dis.Status = 1;
            dis.StoreId = WorkContext.StoreId;
            dis.CreateTime = DateTime.Now;
            dis.LinkMan = user.NickName;
            dis.DisStoreName = user.NickName;
            if (dis.StoreId == 0)
                return PromptView("当前登录用户的所属店铺不正确:0");
            DistributorManager.AddDistributor(dis);

            return PromptView("开通成功");

        }
        public ActionResult EditAgent(int id)
        {
            var dis = DistributorManager.GetDistributor(id);
            var editModel = new AgentEditModel
            {
                Id = dis.Id,
                DisStoreName = dis.DisStoreName,
                ShowLogo = dis.ShowLogo,
                LinkMan = dis.LinkMan,
                PhoneNumber = dis.PhoneNumber
            };
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return View(editModel);
        }
        [HttpPost]
        public ActionResult EditAgent(AgentEditModel model)
        {
            var dis = DistributorManager.GetDistributor(model.Id);
            dis.DisStoreName = model.DisStoreName ?? "";
            dis.LinkMan = model.LinkMan ?? "";
            dis.PhoneNumber = model.PhoneNumber ?? "";
            DistributorManager.UpdateDistributor(dis);

            return PromptView("编辑成功");
        }
        public ActionResult ViewAgent(int id, int pageNumber = 1, int pageSize = 15)
        {
            var dis = DistributorManager.GetDistributor(id);
            var viewModel = CastAgentFromDistributor(dis);
            var br = BrokerageManager.GetBrokerageRequestUserListPage(viewModel.User.Uid, 1, 1, pageNumber, pageSize);
            viewModel.BrokerageRequest = br.Items;
            var pageModel = new PageModel(pageSize, pageNumber, Convert.ToInt32(br.TotalItems));
            viewModel.PageModel = pageModel;
            var team = DistributorManager.GetAgentChildList(id, pageNumber, pageSize);
            var teamPageModel=new PageModel(pageSize,pageNumber,Convert.ToInt32(team.TotalItems));
            viewModel.TeamList = team.Items.Select(CastAgentFromDistributor).ToList();
            viewModel.TeamPageModel = teamPageModel;
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return View(viewModel);
        }
        public ActionResult SetAgentStatus(int id, int status)
        {
            DistributorManager.SetDistributorStatus(id, status);
            return PromptView("操作成功");
        }
        #endregion

        #region 佣金明细

        public ActionResult BrokerageList(string disStoreName, string tradeTimeStart, string tradeTimeEnd, string orderNo, int pageNumber = 1, int pageSize = 15)
        {

            var ts = new DateTime(1900, 1, 1);
            var te = new DateTime(1900, 1, 1);
            if (!string.IsNullOrEmpty(tradeTimeStart))
                DateTime.TryParse(tradeTimeStart, out ts);
            if (!string.IsNullOrEmpty(tradeTimeEnd))
                DateTime.TryParse(tradeTimeEnd, out te);
            var blist = BrokerageManager.GetBrokerageStoreListPage(WorkContext.StoreId, disStoreName, ts, te, orderNo,
                pageNumber, pageSize);
            var pageModel = new PageModel(pageSize, pageNumber, Convert.ToInt32(blist.TotalItems));
            var model = new BrokerageListModel
            {
                BrokerageList = blist.Items.Select(CastFromBrokerage).ToList(),
                PageModel = pageModel,
                DisStoreName = disStoreName,
                TradeTimeStart = tradeTimeStart,
                TradeTimeEnd = tradeTimeEnd,
                OrderNo = orderNo
            };
            return View(model);
        }

        #endregion
        #region 提现申请

        public ActionResult BrokerageRequestList(string disStoreName, string sendTimeStart, string sendTimeEnd, string requestTimeStart, string requestTimeEnd,
            int pageNumber = 1, int pageSize = 15)
        {
            var st = new DateTime(1900, 1, 1);
            var se = new DateTime(1900, 1, 1);
            var rqs = new DateTime(1900, 1, 1);
            var rqe = new DateTime(1900, 1, 1);
            if (!string.IsNullOrEmpty(sendTimeStart))
                DateTime.TryParse(sendTimeStart, out st);
            if (!string.IsNullOrEmpty(sendTimeEnd))
                DateTime.TryParse(sendTimeEnd, out se);
            if (!string.IsNullOrEmpty(requestTimeStart))
                DateTime.TryParse(requestTimeStart, out rqs);
            if (!string.IsNullOrEmpty(requestTimeEnd))
                DateTime.TryParse(requestTimeEnd, out rqe);
            var blist = BrokerageManager.GetBrokerageRequestStoreListPage(WorkContext.StoreId, disStoreName, rqs,
                rqe, st, se, 1, 1, pageNumber, pageSize);
            var pageModel = new PageModel(pageSize, pageNumber, Convert.ToInt32(blist.TotalItems));
            var model = new BrokerageRequestListModel
            {
                BrokerageRequestList = blist.Items.Select(CastFromBrokerageRequest).ToList(),
                PageModel = pageModel,
                DisStoreName = disStoreName,
                RequestTimeStart = requestTimeStart,
                RequestTimeEnd = requestTimeEnd,
                SendTimeStart = sendTimeStart,
                SendTimeEnd = sendTimeEnd
            };
            return View(model);
        }

        public ActionResult BrokerageRequestApproveList(string disStoreName, string sendTimeStart, string sendTimeEnd, string requestTimeStart, string requestTimeEnd,
            int pageNumber = 1, int pageSize = 15)
        {
            var st = new DateTime(1900, 1, 1);
            var se = new DateTime(1900, 1, 1);
            var rqs = new DateTime(1900, 1, 1);
            var rqe = new DateTime(1900, 1, 1);
            if (!string.IsNullOrEmpty(sendTimeStart))
                DateTime.TryParse(sendTimeStart, out st);
            if (!string.IsNullOrEmpty(sendTimeEnd))
                DateTime.TryParse(sendTimeEnd, out se);
            if (!string.IsNullOrEmpty(requestTimeStart))
                DateTime.TryParse(requestTimeStart, out rqs);
            if (!string.IsNullOrEmpty(requestTimeEnd))
                DateTime.TryParse(requestTimeEnd, out rqe);
            var blist = BrokerageManager.GetBrokerageRequestStoreListPage(WorkContext.StoreId, disStoreName, rqs,
                rqe, st, se, 0, -1, pageNumber, pageSize);
            var pageModel = new PageModel(pageSize, pageNumber, Convert.ToInt32(blist.TotalItems));
            var model = new BrokerageRequestListModel
            {
                BrokerageRequestList = blist.Items.Select(CastFromBrokerageRequest).ToList(),
                PageModel = pageModel,
                DisStoreName = disStoreName,
                RequestTimeStart = requestTimeStart,
                RequestTimeEnd = requestTimeEnd,
                SendTimeStart = sendTimeStart,
                SendTimeEnd = sendTimeEnd
            };
            MallUtils.SetAdminRefererCookie(Url.Action("BrokerageRequestApproveList"));
            return View(model);
        }

        public ActionResult ApproveRequest(int id)
        {
            var br = BrokerageManager.GetBrokerageRequest(id);
            br.ApprovedUserId = WorkContext.PartUserInfo.Uid;
            br.ApprovedUserName = WorkContext.PartUserInfo.NickName;
            br.ApprovedTime = DateTime.Now;
            br.Status = 1;
            BrokerageManager.UpdateBrokerageRequest(br);
            return PromptView("审核成功");
        }
        public ActionResult SendRequest(string brsn)
        {
            if (string.IsNullOrEmpty(brsn)) return PromptView("参数格式错误");


            return RedirectToAction("Transfer", "WeChat", new RouteValueDictionary { { "brsn", brsn }, { "sendUserId", WorkContext.Uid } });

        }

        public ActionResult OfflineSendRequest(string brsn)
        {
            if (string.IsNullOrEmpty(brsn)) return PromptView("参数格式错误");
            var brRequest = BrokerageManager.GetBrokerageRequestByBrsn(brsn);

            if (brRequest == null || brRequest.Status != 1)
            {
                return PromptView("参数格式错误");
            }
            if (brRequest.PayStatus == 1) return PromptView("参数格式错误");
            var sendUser = Users.GetPartUserById(WorkContext.Uid);
            
            var record = new BrokerageSendRecord
            {
                BRId = brRequest.Id,
                SendAmount = brRequest.Amount,
                SendTime = DateTime.Now,
                SendUserId = sendUser.Uid,
                SendUserName = sendUser.NickName,
                Status = 1,
                TradeNo = "--",
                TradeType = 99
            };
            var brsid = BrokerageManager.AddBrokerageSendRecord(record);
            if (brsid <= 0) return PromptView("添加打款记录错误");
            brRequest.PayStatus = 1;
            brRequest.SendTime = DateTime.Now;
            BrokerageManager.UpdateBrokerageRequest(brRequest);

            DistributorManager.AppendDistributorRequestBalance(brRequest.UserId, record.SendAmount);
            return PromptView("发放佣金成功");
        }

        #endregion

        #region 私有
        private static DisGradeModel MapFrom(DisGrade grade)
        {
            return new DisGradeModel()
            {
                Id = grade.Id,
                Name = grade.Name,
                Description = grade.Description,
                BrokerageLimit = grade.BrokerageLimit,
                FirstBrokerageRise = grade.FirstBrokerageRise,
                SecondBrokerageRise = grade.SecondBrokerageRise,
                ThirdBrokerageRise = grade.ThirdBrokerageRise,
                IsDefault = grade.IsDefault,
                GradeType = grade.GradeType
            };
        }

        private static DisGrade MapTo(DisGradeModel m)
        {
            return new DisGrade()
            {
                Id = m.Id,
                Name = m.Name,
                Description = m.Description,
                BrokerageLimit = m.BrokerageLimit,
                FirstBrokerageRise = m.FirstBrokerageRise,
                SecondBrokerageRise = m.SecondBrokerageRise,
                ThirdBrokerageRise = m.ThirdBrokerageRise,
                IsDefault = m.IsDefault,
                GradeType = m.GradeType
            };
        }
        private static DistributorViewModel CastFromDistributor(Distributor dis)
        {
            return new DistributorViewModel()
            {
                Id = dis.Id,
                User = Users.GetPartUserById(dis.UserId),
                StoreId = dis.StoreId,
                ShowLogo = dis.ShowLogo,
                Agent = DistributorManager.GetDistributor(dis.AgentDId),
                DisGrade = DistributorManager.GetGrade(dis.GradeId),
                ParentId = dis.ParentId,
                Path = dis.Path,
                OrdersTotal = dis.OrdersTotal,
                OrdersCount = dis.OrdersCount,
                AccountBalance = dis.AccountBalance,
                RequestBalance = dis.RequestBalance,
                IsAgent = dis.IsAgent,
                Status = dis.Status,
                DisLevel = dis.DisLevel,
                CreateTime = dis.CreateTime,
                DisStoreName = dis.DisStoreName,
                LinkMan = dis.LinkMan,
                PhoneNumber = Users.GetPartUserById(dis.UserId).Mobile,
                PendingBalance = BrokerageManager.GetBrokerageRequestUserListPage(dis.UserId,-1,0,1,999).Items.Sum(t=>t.Amount)
            };
        }
        private static AgentViewModel CastAgentFromDistributor(Distributor dis)
        {
            return new AgentViewModel()
            {
                Id = dis.Id,
                User = Users.GetPartUserById(dis.UserId),
                StoreId = dis.StoreId,
                ShowLogo = dis.ShowLogo,
                Agent = DistributorManager.GetDistributor(dis.AgentDId),
                DisGrade = DistributorManager.GetGrade(dis.GradeId),
                ParentId = dis.ParentId,
                Path = dis.Path,
                OrdersTotal = dis.OrdersTotal,
                OrdersCount = dis.OrdersCount,
                AccountBalance = dis.AccountBalance,
                RequestBalance = dis.RequestBalance,
                IsAgent = dis.IsAgent,
                Status = dis.Status,
                DisLevel = dis.DisLevel,
                CreateTime = dis.CreateTime,
                DisStoreName = dis.DisStoreName,
                LinkMan = dis.LinkMan,
                PhoneNumber = dis.PhoneNumber,
                PendingBalance = BrokerageManager.GetBrokerageRequestUserListPage(dis.UserId, -1, 0, 1, 999).Items.Sum(t => t.Amount)
            };
        }

        private static BrokerageModel CastFromBrokerage(Brokerage bro)
        {
            var m = new BrokerageModel
            {
                ApprovedTime = bro.ApprovedTime,
                ApprovedUserId = bro.ApprovedUserId,
                ApprovedUserName = bro.ApprovedUserName,
                BrokerageAmount = bro.BrokerageAmount,
                BrokerageType = bro.BrokerageType,
                Id = bro.Id,
                OrderAmount = bro.OrderAmount,
                OrderNo = bro.OrderNo,
                TradeUserId = bro.TradeUserId,
                Remark = bro.Remark,
                Status = bro.Status,
                StoreId = bro.StoreId,
                TradeTime = bro.TradeTime,
                UserId = bro.UserId,
                BrokerageRise = bro.BrokerageRise

            };
            m.Distributor = DistributorManager.GetDistributorByUserId(m.UserId);
            m.TradeUser = Users.GetPartUserById(m.TradeUserId);
            return m;
        }

        private static BrokerageRequestModel CastFromBrokerageRequest(BrokerageRequest req)
        {
            var m = new BrokerageRequestModel
            {
                Amount = req.Amount,
                ApprovedTime = req.ApprovedTime,
                ApprovedUserId = req.ApprovedUserId,
                ApprovedUserName = req.ApprovedUserName,
                Id = req.Id,
                PayStatus = req.PayStatus,
                PhoneNumber = req.PhoneNumber,
                Remark = req.Remark,
                RequestBankAccount = req.RequestBankAccount,
                RequestBankName = req.RequestBankName,
                RequestOpenId = req.RequestOpenId,
                RequestTime = req.RequestTime,
                RequestType = req.RequestType,
                RequestUserRealName = req.RequestUserRealName,
                SendTime = req.SendTime,
                Status = req.Status,
                UserId = req.UserId,
                UserName = req.UserName,
                Distributor = DistributorManager.GetDistributorByUserId(req.UserId),
                Brsn = req.Brsn
            };
            return m;
        }
        /// <summary>
        /// 分销设置
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult DisGradeSet()
        {
            var model = DistributorManager.GetDistriDisGradeSet(WorkContext.StoreId);
            if (model == null)
            {
                MallUtils.SetAdminRefererCookie(Url.Action("DisGradeSet"));
                return View();
            }
            else
            {
                var editModel = new DistributorSetModel
                {
                    StoreId = model.StoreId,
                    CardSlogan = model.CardSlogan,
                    CardName = model.CardName,
                    LogoShowImg = model.LogoShowImg,
                    LogoType = model.LogoType,
                    Description = model.Description,
                };
                MallUtils.SetAdminRefererCookie(Url.Action("DisGradeSet"));
                return View(editModel);
            }
            
        }
        [HttpPost]
        public ActionResult SaveDisGradeSet(DistributorSetModel dismodel)
        {
            var model = DistributorManager.GetDistriDisGradeSet(WorkContext.StoreId);
            if (model==null)
            {
                var dismodel1 = new DistributorSet();
                dismodel1.StoreId = WorkContext.StoreId;
                dismodel1.CardSlogan = dismodel.CardSlogan;
                dismodel1.Description = string.Empty;
                dismodel1.LogoType = 0;
                dismodel1.LogoShowImg = string.Empty;
                dismodel1.CardName = string.Empty;
               var result=DistributorManager.AddDistributorset(dismodel1);
                if (result > 0)
                {
                    ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
                    return PromptView("添加成功。");
                }
            }
            var card = "";
            if (string.IsNullOrEmpty(dismodel.CardSlogan))
               dismodel.CardSlogan = card;

            DistributorManager.SetDistributorset(dismodel.CardSlogan, WorkContext.StoreId);
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return PromptView("分销设置成功");
        }
        #endregion
    }
}
